// Terminal handler

function Log(msg) {
  var lines = msg.split('\n');
  for (line in lines) {
    var debug = document.getElementById("debug");
    debug.appendChild(document.createElement('br'));

    var text = document.createTextNode(lines[line]);
    debug.appendChild(text);
  }

  // var text_area = document.createElement('textarea');
  // text_area.rows = 5;
  // text_area.cols = 80;
  // text_area.setAttribute('readonly', true);
  // text_area.value = msg;
  // debug.appendChild(text_area);
}

function NewInput() {
  var input_root = document.getElementById("input-root");
  input_root.appendChild(document.createElement('hr'));
  input_root.appendChild(document.createTextNode('WSH> '));
  var text_area = document.createElement('textarea');
  text_area.rows = 1;
  text_area.cols = 100;
  text_area.onchange = InputChanged;
  input_root.appendChild(text_area);
}

function InputChanged() {
  var inputs = document.getElementsByTagName("input");
  var shell_id = inputs[0].value;

  var textarea = event.srcElement;
  textarea.setAttribute('readonly', true);

  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", "/shell/" + shell_id, true);
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      var reply = JSON.parse(xmlhttp.responseText);
      Log("stdout=" + reply.Stdout);
    } else {
      // alert(xmlhttp.readyState);
    }
  };
  xmlhttp.send(textarea.value);

  NewInput();
}

function main() {
  NewInput();
}
